package com.dgut.finaldemo.controller;

import com.dgut.finaldemo.entity.*;
import com.dgut.finaldemo.service.*;
import com.dgut.finaldemo.util.JWTUtil;
import com.dgut.finaldemo.util.R;
import com.dgut.finaldemo.util.TCaptcha;
import com.dgut.finaldemo.util.TCaptchaVerify;
import com.dgut.finaldemo.vo.DataVO;
import com.dgut.finaldemo.vo.RecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentHealthService studentHealthService;

    @Autowired
    private TeacherHealthService teacherHealthService;

    //首页显示
    @RequestMapping("/user")
    @ResponseBody
    public DataVO user(Integer page,Integer limit){
        return userService.findData(page, limit);
    }

    //暂时没用
    @GetMapping("/userHtml")
    public String userHtml(){
        return "user";
    }

    //addUser添加操作的映射
    @RequestMapping("/addUser")
    public String addUSer(){
        return "addUser";
    }

    //添加操作
    @RequestMapping("user/addUserSubmit")
    @ResponseBody
    public R addUserSubmit(User user){
        if(user.getStatus()==null){
            user.setStatus(0);
        }
        if(user.getAdmin()==0){
            userService.addUser(user);
        }
        return R.ok();
    }


    @RequestMapping("user/updateUserSubmit")
    @ResponseBody
    public R updateUser(User user){
        if(user.getStatus()==null){
            user.setStatus(0);
        }else{
            user.setStatus(1);
        }
        userService.updateUser(user);
        return R.ok();
    }

    @RequestMapping("user/deleteUserById")
    @ResponseBody
    public R deleteUserById(Integer uid){
        userService.deleteUserById(uid);
        return R.ok();
    }

    @RequestMapping("user/searchUser")
    @ResponseBody
    public DataVO searchUser(Integer page,Integer limit,Integer uid,String username,String password){
        System.out.println(page);
        System.out.println(limit);
        System.out.println(username);
        System.out.println(password);

        return userService.searchUser(page, limit, uid,username, password);
    }

    @GetMapping("/adminIndex")
    public String adminIndex(){
        return "adminIndex";
    }

    @GetMapping("/userIndex")
    public String userIndex(){
        return "userIndex";
    }

    @PostMapping("/login_end")
    @ResponseBody
    public Map<String,Object> login_end(User user,Model model){
        log.info("用户名：[{}]",user.getUsername());
        log.info("密码：[{}]",user.getPassword());

        System.out.println(user);
        Map<String,Object> map = new HashMap<>();
        try {
            User userDB = userService.queryUserByUsername(user.getUsername());
            if(userDB==null){
                model.addAttribute("MESSAGE","账户不存在");
            }else{
                if(!userDB.getPassword().equals(user.getPassword())){
                    model.addAttribute("MESSAGE","密码错误");
                }else{
                    if(userDB.getStatus()==0){
                        model.addAttribute("MESSAGE","账号被停用");
                    }else{
                        Map<String,String> payload = new HashMap<>();
                        payload.put("uid",userDB.getUid().toString());
                        payload.put("admin",userDB.getAdmin().toString());
                        payload.put("username",userDB.getUsername());
                        payload.put("password",userDB.getUsername());
                        payload.put("status",userDB.getStatus().toString());

                        //生成JWT令牌
                        String token = JWTUtil.getToken(payload);
                        map.put("admin",userDB.getAdmin());
                        map.put("state",true);
                        map.put("msg","认证成功");
                        map.put("token",token);
                    }

                }
            }

        }catch(Exception e){
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    /*@PostMapping("/login_end")
    public String login_end(String username,String password,Model model){
        User user = userService.queryUserByUsername(username);
        if(user==null){
            model.addAttribute("MESSAGE","账号不存在！");
            model.addAttribute("username",username);
            return "login-2";
        }else{
            if(!user.getPassword().equals(password)){
                model.addAttribute("MESSAGE","密码有错误！");
                model.addAttribute("username",username);
                return "login-2";
            }else{
                if(user.getStatus()==1){
                    if(user.getAdmin()==1){
                        model.addAttribute("MESSAGE","登录成功！");
                        model.addAttribute("user",user);
                        Map<String,String> payload = new HashMap<>();
                        payload.put("uid",user.getUid().toString());
                        payload.put("username",user.getUsername());
                        payload.put("password",user.getPassword());
                        String token = JWTUtil.getToken(payload);

                        return "adminIndex";
                    }else {
                        model.addAttribute("MESSAGE","登录成功！");
                        model.addAttribute("user",user);
                        return "userIndex";
                    }
                }else{
                    model.addAttribute("MESSAGE","账号被停用！");
                    model.addAttribute("user",user);
                    return "login-2";
                }

            }
        }
    }*/

    @PostMapping("/register_end")
    public String register_end(String username,String password,String password2,Model model){
        User user = userService.queryUserByUsername(username);
        if(user!=null){
            model.addAttribute("MESSAGE","账户已存在");
            model.addAttribute("username",username);
            return "register-2";
        }else{
            if(!password.equals(password2)){
                model.addAttribute("MESSAGE","密码输入不一致");
                model.addAttribute("username",username);
                return "register-2";
            }else {
                User user1 = new User();
                user1.setUsername(username);
                user1.setPassword(password);
                user1.setAdmin(0);
                user1.setStatus(0);
                userService.addUser(user1);
                model.addAttribute("MESSAGE","注册成功，等待审核！");
                model.addAttribute("username",username);
                model.addAttribute("password",password);
                return "login-2";
            }
        }

    }
    @GetMapping("/logout")
    public String logout() { return "login-2";}

    @PostMapping("/login_front")
    public String login_front(String username,String password,String select,Model model) throws NullPointerException{
        if(select.equals("学生")&&studentService.queryStudentByUsername(username)!=null){
            if(studentService.queryStudentByUsername(username).getPassword().equals(password)){
                Date d=new Date();
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");

                model.addAttribute("id",studentService.queryStudentByUsername(username).getSid());
                model.addAttribute("username",studentService.queryStudentByUsername(username).getUsername());
                model.addAttribute("name",studentService.queryStudentByUsername(username).getName());
                model.addAttribute("date",df.format(d));
                model.addAttribute("clock",studentService.queryStudentByUsername(username).getClock());
                model.addAttribute("select","学生");
                if(studentService.queryStudentByUsername(username).getClock().equals("已打卡")){
                    StudentHealth studentHealth = studentHealthService.queryStudentHealthByDate(username,df.format(d));
                    if(studentHealth!=null){
                        model.addAttribute("temperature",studentHealth.getTemperature());
                        model.addAttribute("area",studentHealth.getArea());
                    }
                }
                return "recordHealth";
            }else{
                model.addAttribute("MESSAGE","账号或者密码错误！");
                model.addAttribute("username",username);
                return "login-1";
            }

        }else if(select.equals("老师")&&teacherService.queryTeacherByUsername(username)!=null){
            if(teacherService.queryTeacherByUsername(username).getPassword().equals(password)){
                Date d=new Date();
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");

                model.addAttribute("id",teacherService.queryTeacherByUsername(username).getTid());
                model.addAttribute("username",teacherService.queryTeacherByUsername(username).getUsername());
                model.addAttribute("name",teacherService.queryTeacherByUsername(username).getName());
                model.addAttribute("date",df.format(d));
                model.addAttribute("clock",teacherService.queryTeacherByUsername(username).getClock());
                model.addAttribute("select","老师");
                if(teacherService.queryTeacherByUsername(username).getClock().equals("已打卡")){
                    TeacherHealth teacherHealth = teacherHealthService.queryTeacherHealthByDate(username,df.format(d));
                    if(teacherHealth!=null){
                        model.addAttribute("temperature",teacherHealth.getTemperature());
                        model.addAttribute("area",teacherHealth.getArea());
                    }
                }
                return "recordHealth";
            }else {
                model.addAttribute("MESSAGE","账号或者密码错误！");
                model.addAttribute("username",username);
                return "login-1";
            }
        }else{
            model.addAttribute("MESSAGE","账号或者密码错误！");
            model.addAttribute("username",username);
            return "login-1";
        }
    }

    @PostMapping("/goRecordHealth")
    public String goRecordHealth(RecordVO recordVO,String select,String clock,Model model) throws NullPointerException{

        System.out.println(recordVO);
        System.out.println(select);
        System.out.println(clock);

        if(clock.equals("未打卡")){
            if(select.equals("学生")){
                StudentHealth studentHealth = new StudentHealth();

                studentHealth.setSid(recordVO.getId());
                studentHealth.setSusername(recordVO.getUsername());
                studentHealth.setSname(recordVO.getName());
                studentHealth.setTemperature(Float.parseFloat(recordVO.getTemperature()));
                studentHealth.setDate(recordVO.getDate());
                studentHealth.setArea(recordVO.getArea());

                System.out.println(studentHealth);

                studentHealthService.addStudentHealth(studentHealth);
                Student student = studentService.queryStudentByUsername(recordVO.getUsername());
                if(student!=null){
                    student.setClock("已打卡");
                    studentService.updateStudent(student);
                }

                modelAdd(recordVO, model);
                model.addAttribute("clock","已打卡");
                model.addAttribute("select","学生");
                return "recordHealth";

            }else if(select.equals("老师")){
                TeacherHealth teacherHealth = new TeacherHealth();
                teacherHealth.setTid(recordVO.getId());
                teacherHealth.setTusername(recordVO.getUsername());
                teacherHealth.setTname(recordVO.getName());
                teacherHealth.setTemperature(Float.parseFloat(recordVO.getTemperature()));
                teacherHealth.setDate(recordVO.getDate());
                teacherHealth.setArea(recordVO.getArea());

                teacherHealthService.addTeacherHealth(teacherHealth);
                Teacher teacher = teacherService.queryTeacherByUsername(recordVO.getUsername());
                if(teacher != null){
                    teacher.setClock("已打卡");
                    teacherService.updateTeacher(teacher);
                }

                modelAdd(recordVO, model);
                model.addAttribute("clock","已打卡");
                model.addAttribute("select","老师");
                return "recordHealth";

            }else {
                model.addAttribute("MESSAGE","出错");
                modelAdd(recordVO, model);
                model.addAttribute("clock","已打卡");
                model.addAttribute("select","老师");
                return "recordHealth";
            }
        }else{
            if(select.equals("学生")){
                modelAdd(recordVO, model);
                model.addAttribute("clock","已打卡");
                model.addAttribute("select","老师");
                return "recordHealth";
            }else if(select.equals("老师")){
                modelAdd(recordVO, model);
                model.addAttribute("clock","已打卡");
                model.addAttribute("select","老师");
                return "recordHealth";
            }else{
                modelAdd(recordVO, model);
                model.addAttribute("MESSAGE","出错");
                return "recordHealth";
            }

        }

    }

    private void modelAdd(RecordVO recordVO, Model model) {
        model.addAttribute("id",recordVO.getId());
        model.addAttribute("username",recordVO.getUsername());
        model.addAttribute("name",recordVO.getName());
        model.addAttribute("date",recordVO.getDate());
        model.addAttribute("temperature",recordVO.getTemperature());
        model.addAttribute("area",recordVO.getArea());
    }

    
    @RequestMapping("/checkLogin")
    @ResponseBody
    public TCaptcha checkLogin(String ticket, String randstr){
        System.out.println(ticket);
        System.out.println(randstr);
       TCaptcha tCaptcha = new TCaptcha();
       tCaptcha.setResult(TCaptchaVerify.verifyTicket(ticket, randstr,"192.168.31.107"));
        return tCaptcha;
    }

    @GetMapping("/loginFront")
    public String login1(){
        return "login-1";
    }

    @GetMapping("/loginEnd")
    public String login2(){
        return "login-2";
    }
    
}
